import { Component, OnInit, ElementRef } from '@angular/core';
import * as D3 from 'd3';
import { Selection } from 'd3';

@Component({
  selector: 'app-d3',
  templateUrl: './d3.component.html',
  styleUrls: ['./d3.component.css']
})
export class D3Component implements OnInit {

  root: HTMLElement;

  data = [
    {x: 215, y: 3.5},
    {x: 321, y: 4},
    {x: 421, y: 5},
    {x: 512, y: 7},
    {x: 621, y: 8},
    {x: 721, y: 9},
    {x: 821, y: 10},
    {x: 921, y: 11},
    {x: 1000, y: 12},
    {x: 1821, y: 17}
  ];

  x;
  y;
  chart: Selection<SVGGElement, {}, null, undefined>;

  margin = {top: 20, right: 30, bottom: 30, left: 40};
  width = 960 - this.margin.left - this.margin.right;
  height = 500 - this.margin.top - this.margin.bottom;

  sum = 1;

  constructor(private el: ElementRef) {
    this.root = el.nativeElement;
  }

  drawData(data: {x: number, y: number}[]) {



    this.y.domain([0, D3.max(data, d => d.y)]);

    const xAxis = D3.axisBottom(this.x).tickFormat(d => {
      const index = + d;
      if (index === 0) {
        return '0';
      }
      if (data.length >= +d) {
        return data[+ d - 1].x + '';
      } else {
        return '';
      }
    });
    const yAxis = D3.axisLeft(this.y);


    this.chart.append('g')
    .attr('class', 'xAxis')
    .attr('transform', 'translate(0,' + this.height + ')')
    .call(xAxis);

    this.chart.select('.yAxis').remove();
    this.chart.append('g')
    .attr('class', 'yAxis')
    .attr('transform', `translate(0,0 )`)
    .call(yAxis);

    const line: any = D3.line<{x: number, y: number}>()
    .x((d, index) => this.x(index + 1))
    .y(d =>  this.y(d.y));

    this.chart.selectAll('.circle').remove();

    this.chart.selectAll('.circle')
      .data(data)
      .enter().append('circle')
      .attr('class', 'circle')
      .attr('r', 5)
      .attr('cy', d => this.y(d.y))
      .attr('cx', (d, index) => this.x(index + 1));

    // 删除线
    this.chart.select('path.line').remove();

    // 添加线条
    this.chart.append('path')
    .datum(data)
    .attr('class', 'line')
    .attr('d', line);
  }
  drawChart() {
    this.x = D3.scaleLinear().range([0, this.width]).domain([0, 10]);

    this.y = D3.scaleLinear().range([this.height, 0]).nice();

    this.chart = D3.select(this.root).select('.chart')
    .attr('width', this.width + this.margin.left + this.margin.right)
    .attr('height', this.height + this.margin.top + this.margin.bottom)
    .append('g')
    .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');


  }

  ngOnInit() {
    D3.interval(() => {
      const data = this.data.slice(0, this.sum);
      this.drawData(data);
      this.sum ++;
    }, 3000);
    this.drawChart();
    // this.drawData(this.data);
  }

}
